<template>
  <el-container>
    <el-header >
      <div>路径:{{ path }}</div>
      <div style="position: relative;float:right;margin-top: -20px">
        <el-button v-if="mode==='0'" size="small" type="primary" icon="el-icon-edit" @click="setEditMode">编辑</el-button>
        <el-button v-else-if="mode==='1'" size="small" type="success" icon="el-icon-check" @click="saveFile">保存</el-button>
      </div>
      <el-divider></el-divider>
    </el-header>

    <el-main>
<!--      <el-collapse-transition>-->
        <MarkdownViewer v-if="mode==='0'&&content.length>0" :md-text="content"></MarkdownViewer>
        <MarkdownEditor v-else-if="mode==='1'" :mdText="content" @update:mdText="content = $event"></MarkdownEditor>
<!--      </el-collapse-transition>-->
    </el-main>
  </el-container>
</template>

<script>
import {getFile, saveTextFile} from "../api/file";
import MarkdownViewer from "../components/MarkdownViewer.vue";
import MarkdownEditor from "../components/MarkdownEditor.vue";

export default {
  name: "Markdown",
  components: {MarkdownEditor, MarkdownViewer},
  data() {
    return {
      path: "",
      content: "",
      mode: 0
    }
  },
  methods: {
    getPath() {
      this.path = this.$route.query.path
      this.mode = this.$route.query.mode
    },
    async showContent() {
      let res = await getFile({path: this.path})
      if (res.status === 404) {
        this.content = "空文件"
      } else {
        this.content = res.data
      }
    },
    setEditMode() {
      // this.$router.push({path: `Markdown`, query: {path: this.path, mode: 1}})
      this.mode = "1"
    },
    async saveFile() {
      let res = await saveTextFile(this.path, this.content)
      if (res.data.code === 0) {
        this.$notify({
          title: '成功',
          message: '保存成功',
          type: 'success'
        });
        this.mode = "0"
        // this.$router.push({path: `Markdown`, query: {path: this.path, mode: 0}})
      } else {
        this.$notify.error({
          title: '错误',
          message: res.data.msg
        });
      }
    },
    //组件内调用
    saveContent(value) {
      this.content = value
    }
  },
  mounted() {
    this.getPath()
    this.showContent()
  }
}
</script>

<style scoped>

</style>
